package br.com.timecardforpeon.csv;

import static br.com.timecardforpeon.util.Util.DATE_FORMAT_FOR_VIEW;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.ParseException;
import java.util.Date;
import java.util.List;
import java.util.Map;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Environment;
import android.util.Log;
import android.widget.Toast;
import br.com.timecardforpeon.R;
import br.com.timecardforpeon.domain.Day;
import br.com.timecardforpeon.domain.Entry;
import br.com.timecardforpeon.domain.EntryPerDay;
import br.com.timecardforpeon.sqlite.domain.EntryDao;
import br.com.timecardforpeon.util.Util;

public class ExportCsvTask extends AsyncTask<String, Void, Boolean> {

	private final Context context;
	private final ProgressDialog dialog;
	private CharSequence fromDate;
	private CharSequence toDate;

	public ExportCsvTask(Context context, CharSequence fromDate, CharSequence toDate) {
		super();
		this.context = context;
		this.dialog = new ProgressDialog(context);
		this.fromDate = fromDate;
		this.toDate = toDate;
	}

	@Override
	protected void onPreExecute() {
		this.dialog.setMessage("Exporting database...");
		this.dialog.show();
	}

	protected Boolean doInBackground(final String... args) {

		File exportDir = new File(Environment.getExternalStorageDirectory(), "");

		if (!exportDir.exists()) {
			exportDir.mkdirs();
		}

		File file = new File(exportDir, "excelDB.csv");

		try {

			file.createNewFile();
			BufferedWriter writer = new BufferedWriter(new FileWriter(file));

			EntryDao dao = new EntryDao(context);
			
			List<Entry> entries = dao.listByPeriod(this.getFromDate(), this.getToDate());
			Map<Day, EntryPerDay> entriesPerDay = Entry.organizeEntriesPerDay(entries);
			int maxEntries = Entry.getMaxEntriesPerDay(entriesPerDay);
			
			writer.write(this.createCsvHeader(maxEntries));
			writer.newLine();
			
			int totalMinutes = 0;
			for (Day day : entriesPerDay.keySet()) {
				
				EntryPerDay entryPerDay = entriesPerDay.get(day);
				totalMinutes += entryPerDay.getTotalMinutes();
				
				writer.write(entryPerDay.createCsv(maxEntries));
				writer.newLine();
			}
			
			writer.write(this.createCsvFooter(maxEntries, totalMinutes));
			
			writer.flush();
			writer.close();
			
			return true;
		}
		catch (Exception e) {

			Log.e("timeCard4Peon", e.getMessage(), e);
			return false;
		}
	}

	private String createCsvHeader(int maxEntries) throws IOException {
		
		
		StringBuilder sb = new StringBuilder();
		sb
			.append(this.context.getString(R.string.date))
			.append(";");

		for (int i = 0; i < maxEntries; i++) {
		
			sb
				.append(this.context.getString(R.string.checkIn))
				.append(";")
				.append(this.context.getString(R.string.checkOut))
				.append(";");
		}
		
		return sb
				.append(this.context.getString(R.string.total))
				.append(";")
				.append(this.context.getString(R.string.notes))
				.append(";")
				.toString();
	}
	
	private String createCsvFooter(int maxEntries, int totalMinutes) {
		
		StringBuilder sb = new StringBuilder();
		
		sb.append(";");
		
		for (int i = 0; i < maxEntries; i++) {
			
			sb
				.append(";")
				.append(";");
		}
		
		return sb
				.append(Util.getTotalHours(totalMinutes))
				.append(";")
				.append(";")
				.toString();
	}
	
	private Date getFromDate() throws ParseException {
		return Util.stringToDate(DATE_FORMAT_FOR_VIEW, this.fromDate.toString());
	}
	
	private Date getToDate() throws ParseException {
		return Util.stringToDate(DATE_FORMAT_FOR_VIEW, this.toDate.toString());
	}

	@Override
	protected void onPostExecute(final Boolean success) {

		if (this.dialog.isShowing()) {
			this.dialog.dismiss();
		}

		if (success) {

			Toast.makeText(this.context, "Export successful!", Toast.LENGTH_SHORT).show();
			return;
		}
		
		Toast.makeText(this.context, "Export failed", Toast.LENGTH_SHORT).show();
	}
}
